package com.vv.tools.common.util;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileReplace {

    private static final String READ_FILE = "classpath:data/read.md";

    private static final String WRITE_FILE = "classpath:data/write.md";

    private static final Map<String, String> REPLACEMAP = new ConcurrentHashMap<>();

    static {
        REPLACEMAP.put("\n### \\d+.(\\d+)", "\n### $1.");
        REPLACEMAP.put("\n#### (.+)", "\n**$1**");
        REPLACEMAP.put("\n## .+练习题.*", "\n## 综合练习");
        REPLACEMAP.put("\n## 1.", "\n## 一、");
        REPLACEMAP.put("\n## 2.", "\n## 二、");
        REPLACEMAP.put("\n## 3.", "\n## 三、");
        REPLACEMAP.put("\n## 4.", "\n## 四、");
        REPLACEMAP.put("\n## 5.", "\n## 五、");
        REPLACEMAP.put("\n## 6.", "\n## 六、");
        REPLACEMAP.put("\n## 7.", "\n## 七、");
        REPLACEMAP.put("\n## 8.", "\n## 八、");
        REPLACEMAP.put("\n## 9.", "\n## 九、");
        REPLACEMAP.put("\n## 10.", "\n## 十、");
        REPLACEMAP.put("\n## \\*\\*1. (.+)\\*\\*", "\n## 一、$1");
        REPLACEMAP.put("\n## \\*\\*2. (.+)\\*\\*", "\n## 二、$1");
        REPLACEMAP.put("\n## \\*\\*3. (.+)\\*\\*", "\n## 三、$1");
        REPLACEMAP.put("\n## \\*\\*4. (.+)\\*\\*", "\n## 四、$1");
        REPLACEMAP.put("\n## \\*\\*5. (.+)\\*\\*", "\n## 五、$1");
        REPLACEMAP.put("\n## \\*\\*6. (.+)\\*\\*", "\n## 六、$1");
        REPLACEMAP.put("\n## \\*\\*7. (.+)\\*\\*", "\n## 七、$1");
        REPLACEMAP.put("\n## \\*\\*8. (.+)\\*\\*", "\n## 八、$1");
        REPLACEMAP.put("\n## \\*\\*9. (.+)\\*\\*", "\n## 九、$1");
        REPLACEMAP.put("\n## \\*\\*10. (.+)\\*\\*", "\n## 十、$1");
        REPLACEMAP.put("\\*\\*\\*\\*", "**");
    }

    public static void main(String[] args) {
        // 读取文件
        String content = readFile();

        // 替换
        String replaceContent = replace(content);

        // 保存文件
        saveFile(replaceContent);
    }

    private static void saveFile(String replaceContent) {
        FileUtils.write(Objects.requireNonNull(FileUtils.getClassPathFile(WRITE_FILE)), replaceContent);
    }

    private static String replace(String content) {
        AtomicReference<String> sar = new AtomicReference<>(content);
        REPLACEMAP.forEach((k, v) -> {
            Matcher matcher = Pattern.compile(k).matcher(sar.get());
            if (matcher.find()) {
                sar.set(matcher.replaceAll(v));
            }
        });
        return sar.get();
    }

    private static String readFile() {
        return FileUtils.read(Objects.requireNonNull(FileUtils.getClassPathFile(READ_FILE)));
    }

}
